package com.quanshu.exchange.ui.gui.profile;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.quanshu.exchange.R;
import com.quanshu.exchange.support.api.ShopInterface;
import com.quanshu.exchange.support.entity.AddressEntity;
import com.quanshu.exchange.support.net.BaseResponse;
import com.quanshu.exchange.support.net.core.BaseObserver;
import com.quanshu.exchange.support.net.core.BaseTransformer;
import com.quanshu.exchange.support.net.core.NetClient;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.LogUtil;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.base.recycler.BaseViewHolder;
import com.quanshu.exchange.ui.base.recycler.DataDisplayer;
import com.quanshu.exchange.ui.base.recycler.LayoutWrapper;
import com.quanshu.exchange.ui.base.recycler.SingleAdapter;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 收货地址
 * Created by xiniu003 on 2018/1/2.
 */

public class DeliveryAddressActivity extends BaseActivity {

    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.delivery_address_no)
    LinearLayout deliveryAddressNo;
    @BindView(R.id.delivery_address_list)
    RecyclerView deliveryAddressList;
    @BindView(R.id.delivery_address_llt)
    LinearLayout deliveryAddressLlt;
    @BindView(R.id.add_delivery_address)
    LinearLayout addDeliveryAddress;

    private List<AddressEntity> datas;
    private SingleAdapter<AddressEntity> adapter;

    private String flag;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_delivery_address);
        ButterKnife.bind(this);
        initAdapter();

        flag = getIntent().getStringExtra("FLAG");

        getAddressList();
        initListener();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {//当返回按键被按下
            Intent intent = getIntent();
            setResult(RESULT_OK, intent);
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    private void initListener() {

        RxViewHelper.getInstance().clicks(back, aVoid -> {
            Intent intent = getIntent();
            setResult(RESULT_OK, intent);
            finish();
        });

        RxViewHelper.getInstance().clicks(addDeliveryAddress, aVoid -> {

            Intent intent = new Intent(DeliveryAddressActivity.this, AddDelivryAddressActivity.class);
            intent.putExtra("add", "新增");
            startActivityForResult(intent, 8);

        });
    }

    private void initAdapter() {
        deliveryAddressList.setLayoutManager(new LinearLayoutManager(DeliveryAddressActivity.this));
        adapter = new SingleAdapter<>(new DataDisplayer<AddressEntity>(DeliveryAddressActivity.this,
                R.layout.item_delivery_address) {
            @Override
            public void bindData(BaseViewHolder holder,
                                 LayoutWrapper<AddressEntity> wrapper,
                                 AddressEntity item,
                                 int position) {
                holder.setText(R.id.delivery_address_name, item.getAccept_name());
                holder.setText(R.id.delivery_address_phone, item.getMobile());
                holder.setText(R.id.delivery_address_privoce,
                        item.getProvince_val() + item.getCity_val() + item.getArea_val());
                holder.setText(R.id.delivery_address_details, item.getAddress());

                ImageButton imageButton = holder.getView(R.id.set_address_default_image);
                if (item.getIs_default() != null && item.getIs_default().equals("1")) {
                    imageButton.setSelected(true);
                } else {
                    imageButton.setSelected(false);
                }

                TextView addressDefault = holder.getView(R.id.address_default);

                if (item.getIs_default().equals("1")) {
                    addressDefault.setVisibility(View.VISIBLE);
                } else {
                    addressDefault.setVisibility(View.GONE);
                }

                //设为默认地址
                holder.setOnClickListener(R.id.set_address_default, view -> {
//                    setDefaultAddr(position);
                });

                //修改地址
                holder.setOnClickListener(R.id.edit_address_llt, view -> {
                    Intent intent = new Intent(DeliveryAddressActivity.this,
                            AddDelivryAddressActivity.class);
                    intent.putExtra("add", "修改");//新增，修改 - 标识
                    intent.putExtra("AddressEntity", item);
                    startActivityForResult(intent, 7);
                });

                //删除地址
                holder.setOnClickListener(R.id.delete_address_llt, view -> {

                    if (item.getIs_default().equals("1")) {

                        DialogDeleteAddressHint dialogDeleteAddressHint = new
                                DialogDeleteAddressHint(DeliveryAddressActivity.this);
                        dialogDeleteAddressHint.show();

                    } else {

                        getDelAddrByAddrId(position);
                    }
                });
            }
        });
        deliveryAddressList.setAdapter(adapter);
    }


    //设置默认收货地址
    private void setDefaultAddr(int position) {
        NetClient.getInstance().getShopService(ShopInterface.class)
                .setDefaultAddr(AppUtils.getSignParams(datas.get(position).getId(), String.valueOf(currentUser.getId())), datas.get(position).getId(), String.valueOf(currentUser.getId()))
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        getAddressList();
                        adapter.notifyDataSetChanged();
                        LogUtil.print(response.getMsg());
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        super.onFailure(e);
                    }
                });
    }

    //删除收货地址
    private void getDelAddrByAddrId(int position) {
        NetClient.getInstance().getShopService(ShopInterface.class)
                .getDelAddrByAddrId(AppUtils.getSignParams(datas.get(position).getId(), String.valueOf(currentUser.getId())), datas.get(position).getId(), String.valueOf(currentUser.getId()))
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        if (position == datas.size() - 1) {
                            getAddressList();
                            initAdapter();
                        } else {
                            datas.remove(position);
                            adapter.notifyItemRemoved(position);
                            adapter.notifyDataSetChanged();
                        }
                        LogUtil.print(response.getMsg());
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        LogUtil.printException(e);
                    }
                });
    }

    //获取收获地址
    private void getAddressList() {
        NetClient.getInstance().getShopService(ShopInterface.class)
                .getAddressList(AppUtils.getSignParams(String.valueOf(currentUser.getId())), String.valueOf(currentUser.getId()))
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse<List<AddressEntity>>>() {
                    @Override
                    public void onSuccess(BaseResponse<List<AddressEntity>> response) {

                        if (response.getData() != null && response.getData().size() > 0) {
                            deliveryAddressNo.setVisibility(View.GONE);
                            datas = response.getData();
                            doIntentAdd();
                            adapter.setData(datas);
                        } else {
                            deliveryAddressNo.setVisibility(View.VISIBLE);
                        }
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        LogUtil.printException(e);
                    }
                });
    }

    private void doIntentAdd() {
        if (flag == null) {

        } else if (flag.equals("flag") && datas == null) {
            Intent intent = new Intent(DeliveryAddressActivity.this, AddDelivryAddressActivity.class);
            intent.putExtra("add", "新增");
            startActivityForResult(intent, 8);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            if (requestCode == 7) {
                //修改
                getAddressList();
                adapter.notifyDataSetChanged();
            }

            if (requestCode == 8) {
                //新建
                getAddressList();
                adapter.notifyDataSetChanged();
            }
        }
    }
}
